package com.down.main;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.wb.swt.SWTResourceManager;

import com.down.utls.LayoutUtils;
import com.down.utls.ThreadPool;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.dialect.Sqlite3Dialect;
import com.jfinal.plugin.druid.DruidPlugin;
import com.keeley.core.DownFileFetch;
import com.keeley.core.DownFileInfoBean;
import com.keeley.listen.DownListener;

public class MyHome {

	protected Shell shell;
	private Button button;
	private Button button_1;
	private Button button_2;
	private Button button_3;
	private Table table;

	private DruidPlugin d;
	private ActiveRecordPlugin arp;
	private List<Record> alldata;
	private TableItem item;

	/**
	 * Launch the application.
	 * 
	 * @param args
	 */

	public static void main(String[] args) {
		try {
			MyHome window = new MyHome();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();

		startupsqlite();
		LayoutUtils.center(shell);
		shell.setMaximized(true);
		shell.setLayout(new FillLayout(SWT.HORIZONTAL));

		Composite composite = new Composite(shell, SWT.NONE);
		composite.setLayout(new FormLayout());

		Composite composite_1 = new Composite(composite, SWT.BORDER);
		composite_1.setLayout(new FillLayout(SWT.HORIZONTAL));
		FormData fd_composite_1 = new FormData();
		fd_composite_1.bottom = new FormAttachment(100);
		fd_composite_1.left = new FormAttachment(0);
		fd_composite_1.top = new FormAttachment(0, 41);
		fd_composite_1.right = new FormAttachment(100);
		composite_1.setLayoutData(fd_composite_1);

		SashForm sashForm = new SashForm(composite_1, SWT.SMOOTH);

		Composite composite_2 = new Composite(sashForm, SWT.BORDER);
		composite_2.setLayout(new FormLayout());

		Button btnNewButton = new Button(composite_2, SWT.NONE);
		btnNewButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				searchtables(StaticInfo.isdowning, StaticInfo.stop);
			}
		});
		FormData fd_btnNewButton = new FormData();
		fd_btnNewButton.right = new FormAttachment(100, -17);
		fd_btnNewButton.left = new FormAttachment(0, 16);
		fd_btnNewButton.top = new FormAttachment(0, 47);
		btnNewButton.setLayoutData(fd_btnNewButton);
		btnNewButton.setText("下载任务");

		Button btnNewButton2 = new Button(composite_2, SWT.NONE);
		btnNewButton2.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				searchtables(StaticInfo.ok);
			}
		});
		FormData fd_btnNewButton2 = new FormData();
		fd_btnNewButton2.top = new FormAttachment(btnNewButton, 20);
		fd_btnNewButton2.left = new FormAttachment(btnNewButton, 0, SWT.LEFT);
		fd_btnNewButton2.right = new FormAttachment(100, -17);
		btnNewButton2.setLayoutData(fd_btnNewButton2);
		btnNewButton2.setText("已下载");

		Composite composite_3 = new Composite(sashForm, SWT.BORDER);
		composite_3.setLayout(new FormLayout());

		Composite composite_5 = new Composite(composite_3, SWT.NONE);
		composite_5.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		composite_5.setLayout(new FormLayout());
		FormData fd_composite_5 = new FormData();
		fd_composite_5.bottom = new FormAttachment(0, 50);
		fd_composite_5.top = new FormAttachment(0);
		fd_composite_5.left = new FormAttachment(0);
		fd_composite_5.right = new FormAttachment(100);
		composite_5.setLayoutData(fd_composite_5);

		Composite composite_6 = new Composite(composite_3, SWT.NONE);
		FormData fd_composite_6 = new FormData();
		fd_composite_6.bottom = new FormAttachment(100);
		fd_composite_6.right = new FormAttachment(100);
		fd_composite_6.top = new FormAttachment(composite_5, 1);

		button = new Button(composite_5, SWT.NONE);
		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				addone();
			}
		});
		FormData fd_button = new FormData();
		fd_button.top = new FormAttachment(0, 10);
		fd_button.left = new FormAttachment(0, 31);
		button.setLayoutData(fd_button);
		button.setText("新建下载任务");

		button_1 = new Button(composite_5, SWT.NONE);
		button_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				detailjob();
			}
		});
		FormData fd_button_1 = new FormData();
		fd_button_1.top = new FormAttachment(button, 0, SWT.TOP);
		fd_button_1.left = new FormAttachment(button, 25);
		button_1.setLayoutData(fd_button_1);
		button_1.setText("查看任务");

		button_2 = new Button(composite_5, SWT.NONE);
		button_2.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				stopall();

			}
		});
		FormData fd_button_2 = new FormData();
		fd_button_2.top = new FormAttachment(button, 0, SWT.TOP);
		fd_button_2.left = new FormAttachment(button_1, 28);
		button_2.setLayoutData(fd_button_2);
		button_2.setText("暂停");

		button_3 = new Button(composite_5, SWT.NONE);
		button_3.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				startall();

			}
		});
		FormData fd_button_3 = new FormData();
		fd_button_3.bottom = new FormAttachment(button, 0, SWT.BOTTOM);
		fd_button_3.left = new FormAttachment(button_2, 31);
		button_3.setLayoutData(fd_button_3);
		button_3.setText("启动");
		composite_6.setLayout(new FillLayout(SWT.HORIZONTAL));
		fd_composite_6.left = new FormAttachment(0);
		composite_6.setLayoutData(fd_composite_6);

		table = new Table(composite_6, SWT.BORDER | SWT.FULL_SELECTION);
		table.setLinesVisible(true);
		table.setHeaderVisible(true);

		TableColumn tableColumn_1 = new TableColumn(table, SWT.NONE);
		tableColumn_1.setWidth(100);
		tableColumn_1.setText("任务编号");

		TableColumn tableColumn_2 = new TableColumn(table, SWT.NONE);
		tableColumn_2.setWidth(800);
		tableColumn_2.setText("下载地址");

		TableColumn tableColumn_3 = new TableColumn(table, SWT.NONE);
		tableColumn_3.setWidth(144);
		tableColumn_3.setText("下载状态");
		TableColumn tableColumn_4 = new TableColumn(table, SWT.NONE);
		tableColumn_4.setWidth(144);
		tableColumn_4.setText("文件大小");
		sashForm.setWeights(new int[] { 1, 6 });

		Composite composite_4 = new Composite(composite, SWT.NONE);
		composite_4.setLayout(new FillLayout(SWT.HORIZONTAL));
		FormData fd_composite_4 = new FormData();
		fd_composite_4.right = new FormAttachment(100);
		fd_composite_4.top = new FormAttachment(0);
		fd_composite_4.left = new FormAttachment(0);
		fd_composite_4.bottom = new FormAttachment(0, 40);
		composite_4.setLayoutData(fd_composite_4);

		ToolBar toolBar = new ToolBar(composite_4, SWT.FLAT | SWT.RIGHT);

		ToolItem toolItem = new ToolItem(toolBar, SWT.NONE);
		toolItem.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Folder f = new Folder(shell, 0);
				f.open();
			}
		});
		toolItem.setText("下载目录");
		toolItem.setImage(SWTResourceManager.getImage(MyHome.class, "/javax/swing/plaf/metal/icons/Inform.gif"));

		ToolItem toolItem_2 = new ToolItem(toolBar, SWT.NONE);
		toolItem_2.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Count f = new Count(shell, 0);
				f.open();
			}
		});
		toolItem_2.setText("最大下载");
		toolItem_2.setImage(SWTResourceManager.getImage(MyHome.class, "/javax/swing/plaf/metal/icons/Error.gif"));

		ToolItem toolItem_1 = new ToolItem(toolBar, SWT.NONE);
		toolItem_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				MessageDialog.openInformation(shell, "版本信息", "断点续传下载工具,V1.6");
				return;
			}
		});
		toolItem_1.setText("版本");
		toolItem_1.setImage(
				SWTResourceManager.getImage(MyHome.class, "/org/eclipse/jface/dialogs/images/message_info.png"));
		shell.open();
		shell.layout();
		shell.addDisposeListener(new DisposeListener() {

			@Override
			public void widgetDisposed(DisposeEvent e) {
				// TODO Auto-generated method stub
				closesqlite();
			}
		});
		searchtables(StaticInfo.isdowning, StaticInfo.stop);
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}

	protected void startall() {
		// TODO Auto-generated method stub

		int selectionIndex = table.getSelectionIndex();
		if (selectionIndex == -1) {
			MessageDialog.openError(shell, "尚未选择数据", "请选择一个下载任务");
			return;
		} else {
			if (selectionIndex != -1) {
				final String id = table.getItem(selectionIndex).getText(0);
				String sta = table.getItem(selectionIndex).getText(2);
				if (StaticInfo.isdowning.equals(sta) || StaticInfo.ok.equals(sta)) {
					MessageDialog.openError(shell, "启动任务", "您只能启动一个暂停的下载任务!");
					return;
				}
				
				Record e = Db.findFirst("select * from down where id=?;", id);
				if (null != e) {
					Record r = Db.findFirst("select * from config where name='mulu'");
					DownFileInfoBean bean = new DownFileInfoBean(e.getStr("url"), r.getStr("value"), e.getStr("filename"), 5,
							true, null);

					DownFileFetch fileFetch = null;
					try {
						// downidk = downid;
						fileFetch = new DownFileFetch(bean, Integer.parseInt(id));
						fileFetch.addListener(new DownListener() {
							public void success() {
								System.out.println("下载成功!来自myhome重新启动任务的成功回调  313行 回调监控");

								ThreadPool.deletethread(Integer.parseInt(id), StaticInfo.ok);
								searchtables(StaticInfo.isdowning, StaticInfo.stop);
							}
						});
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
				
				//ThreadPool.startbyid(Integer.parseInt(id), shell);
				//Db.update("update down set downstatus=? where id=?;", StaticInfo.isdowning, id);
				searchtables(StaticInfo.isdowning, StaticInfo.stop);
			}
		}
	}

	protected void detailjob() {
		// TODO Auto-generated method stub
		int selectionIndex = table.getSelectionIndex();
		if (selectionIndex == -1) {
			MessageDialog.openError(shell, "尚未选择数据", "请选择一个下载任务");
			return;
		} else {
			if (selectionIndex != -1) {
				String id = table.getItem(selectionIndex).getText(0);
				Record e = Db.findFirst("select * from down where id=?;", id);
				Addnewdownshowinfo b = new Addnewdownshowinfo(shell, 0, e.getStr("url"), e.getStr("logs"));
				b.open();
			}
		}
	}

	protected void stopall() {
		// TODO Auto-generated method stub
		int selectionIndex = table.getSelectionIndex();
		if (selectionIndex == -1) {
			MessageDialog.openError(shell, "尚未选择数据", "请选择一个下载任务");
			return;
		} else {
			if (MessageDialog.openConfirm(shell, "暂停下载任务?", "确认暂停该下载任务,将支持断点续传!") && selectionIndex != -1) {
				String id = table.getItem(selectionIndex).getText(0);
				String sta = table.getItem(selectionIndex).getText(2);
				if (StaticInfo.stop.equals(sta)) {
					MessageDialog.openInformation(shell, "任务已经暂停", "当前任务已经暂停!");
					return;
				}
				ThreadPool.stopbyid(Integer.parseInt(id), shell);
				Db.update("update down set downstatus=? where id=?;", StaticInfo.stop, id);
				searchtables(StaticInfo.isdowning, StaticInfo.stop);
			}
		}
	}

	protected void addone() {
		// TODO Auto-generated method stub
		Addnewdown a = new Addnewdown(shell, SWT.NONE);
		a.open();
		searchtables(StaticInfo.isdowning, StaticInfo.stop);
	}

	protected void closesqlite() {
		// TODO Auto-generated method stub
		System.out.println("系统开始关闭了....");
		d.stop();
		arp.stop();

		Addnewdown.closetd();
		ThreadPool.close();
	}

	private void startupsqlite() {
		// TODO Auto-generated method stub
		System.out.println("系统开始启动了....");
		d = new DruidPlugin("jdbc:sqlite:images\\download.db", "", "");
		d.setDriverClass("org.sqlite.JDBC");

		arp = new ActiveRecordPlugin(d);
		arp.setDialect(new Sqlite3Dialect());

		// _MappingKit.mapping(arp); 不映射只能用record
		// _MappingKit.mapping(arp);
		d.start();
		arp.start();

		// test();
	}

	private void test() {
		// TODO Auto-generated method stub
		java.util.List<Record> s = Db.find("select * from down");
		System.out.println(s.size());
		for (Record u : s) {

			System.out.println(u.getInt("id"));
		}
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		shell = new Shell();
		shell.setImage(SWTResourceManager.getImage(MyHome.class, "/icons/full/dview16/tasks_tsk.png"));
		shell.setSize(1266, 687);
		shell.setText("断点续传下载");

	}

	private void searchtables(String... status) {
		alldata = null;
		table.clearAll();

		for (Item i : table.getItems()) {
			i.dispose();
		}
		table.redraw();
		int i = table.getColumnCount();
		List<Record> all = new ArrayList<Record>();
		for (String k : status) {
			List<Record> li = Db.find("select * from down where downstatus=?;", k);
			all.addAll(li);
		}

		alldata = all;

		for (Record tr : alldata) {
			item = new TableItem(table, SWT.NONE);

			item.setText(0, Integer.toString(tr.getInt("id")));
			item.setText(1, tr.getStr("url"));
			item.setText(2, tr.getStr("downstatus"));
			item.setText(3, tr.getStr("filesize"));

			/*
			 * TableEditor editor = new TableEditor(table);
			 * editor.horizontalAlignment = SWT.CENTER;// 设置显示在左边
			 * editor.minimumWidth = 30;// 设置显示宽度 editor.grabHorizontal = true;
			 * 
			 * Composite g = new Composite(table, 0); g.setLayout(new
			 * FillLayout());
			 * 
			 * Button t1 = new Button(g, 0); t1.setText("暂停"); Button t2 = new
			 * Button(g, 0); t2.setText("启动"); Button t3 = new Button(g, 0);
			 * t3.setText("删除"); editor.setEditor(g, item, 3)
			 */;
		}
	}
}
